/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers.changePassword;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputSecret;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Ida
 */
@FacesValidator("javaclass.PasswordValidator")
public class PasswordValidator implements Validator {
    private static final String DIGIT_RE = ".*\\d+.*",
                                SPECIAL_RE = ".*[^\\s\\w\\d]+.*";
    private static int MIN_TEGN = 6;

    public PasswordValidator() {
    }
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        HtmlInputSecret inputcomponent = (HtmlInputSecret) component;

        final String secondVal = value.toString();
        /*vi bruker matches som er en innebygd metode i klassen String **/
        final boolean hasDigit = secondVal.matches(DIGIT_RE),
                      hasSpecial = secondVal.matches(SPECIAL_RE),
                      isLongEnough = secondVal.length() >= MIN_TEGN;
        final boolean isAccepted = hasDigit && hasSpecial && isLongEnough;

        if (!isAccepted) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    inputcomponent.getLabel() + " Validation Error: Feil i passord",
                    inputcomponent.getLabel() + " "));
        }
    }

}
